package com.zealcomm.ivcscustomer.fragment

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.bumptech.glide.Glide
import com.zco.util.Base64Util
import com.zco.util.LogUtil
import com.zco.util.StringUtil
import com.zco.util.ToastUtil
import com.zco.util.listener.CustomOnClickListener
import com.zco.base.Constants
import com.zco.base.ServerCallback
import com.zealcomm.commonui.base.BaseFragment2
import com.zealcomm.ivcscustomer.R
import com.zealcomm.ivcscustomer.activity.CameraActivity
import com.zealcomm.ivcscustomer.app.IvcsApplication
import com.zco.ivcs.customer.base.entity.SubmitIDAndBankInfoResultBean
import com.zealcomm.ivcscustomer.databinding.FragmentIdCardAndBankBinding
import com.zealcomm.ivcscustomer.service.MainActivity
import com.zealcomm.utils.bindView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.io.FileOutputStream

/**
 * 提交身份证和银行卡图片界面
 */
class IDCardAndBankFragment() : BaseFragment2(R.layout.fragment_id_card_and_bank) {

    private val CAPTURE_ID_CARD_FRONT_PICTURE = 101
    private val CAPTURE_ID_CARD_BACK_PICTURE = 102
    private val CAPTURE_BANK_PICTURE = 103
    private val CAPTURE_SELF_PICTURE = 104
    private val binding: FragmentIdCardAndBankBinding by bindView()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setListeners()
    }

    private fun setListeners() {
        binding.tvSubmit.setOnClickListener(object : CustomOnClickListener<Any>() {
            override fun onCustomClick(view: View?) {
                (holdingActivity as MainActivity).idCardAndBankInfo.let {
                    it.address = binding?.etAddress?.text.toString()
                    it.company = binding?.etCompany?.text.toString()
                    if (StringUtil.hasEmptyValue(
                            it.backPhoto,
                            it.bankCardPhoto,
                            it.frontPhoto,
                            it.selfie
                        )
                    ) {
                        ToastUtil.showShort("请完善资料")
                        return
                    }
                }
                if (TextUtils.isEmpty(binding?.etAddress?.text)) {
                    ToastUtil.showShort("请填写地址")
                    return
                }
                if (TextUtils.isEmpty(binding?.etCompany?.text)) {
                    ToastUtil.showShort("请填写公司名称")
                    return
                }

                IvcsApplication.ivcsCustomer?.submitIDCardAndBankInfo(
                    (holdingActivity as MainActivity).idCardAndBankInfo,
                    object : ServerCallback<SubmitIDAndBankInfoResultBean>() {

                        override fun onSuccess(t: SubmitIDAndBankInfoResultBean?) {
                            // 坐席接通后才会发送，所以暂时存着，不做任何处理
                            t?.data?.id?.let {
                                (holdingActivity as MainActivity).formId = it
                            }
                            (holdingActivity as MainActivity).showServiceList()
                        }

                        override fun failedResponse(result: String?) {
                            showToast(result)
                        }
                    }
                )

            }
        })
        binding.ivIdCardFront.setOnClickListener(object : CustomOnClickListener<Any>() {
            override fun onCustomClick(view: View?) {
                val intent = Intent(holdingActivity, CameraActivity::class.java)
                intent.putExtra(
                    CameraActivity.PLACEHOLDER_TYPE,
                    CameraActivity.PLACEHOLDER_TYPE_ID_CARD_FRONT
                )
                startActivityForResult(intent, CAPTURE_ID_CARD_FRONT_PICTURE)
            }
        })
        binding.ivIdCardBack.setOnClickListener(object : CustomOnClickListener<Any>() {
            override fun onCustomClick(view: View?) {
                val intent = Intent(holdingActivity, CameraActivity::class.java)
                intent.putExtra(
                    CameraActivity.PLACEHOLDER_TYPE,
                    CameraActivity.PLACEHOLDER_TYPE_ID_CARD_BACK
                )
                startActivityForResult(intent, CAPTURE_ID_CARD_BACK_PICTURE)
            }
        })
        binding.ivBankFront.setOnClickListener(object : CustomOnClickListener<Any>() {
            override fun onCustomClick(view: View?) {
                val intent = Intent(holdingActivity, CameraActivity::class.java)
                intent.putExtra(
                    CameraActivity.PLACEHOLDER_TYPE,
                    CameraActivity.PLACEHOLDER_TYPE_DEFAULT
                )
                startActivityForResult(intent, CAPTURE_BANK_PICTURE)
            }
        })
        binding.ivSelf.setOnClickListener(object : CustomOnClickListener<Any>() {
            override fun onCustomClick(view: View?) {
                val intent = Intent(holdingActivity, CameraActivity::class.java)
                intent.putExtra(
                    CameraActivity.PLACEHOLDER_TYPE,
                    CameraActivity.PLACEHOLDER_TYPE_DEFAULT
                )
                startActivityForResult(intent, CAPTURE_SELF_PICTURE)
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            data?.getParcelableExtra<Uri>(CameraActivity.PICTURE_PATH)?.let {
                GlobalScope.launch(Dispatchers.IO) {
                    val file = File(requireContext().filesDir, "${System.currentTimeMillis()}.jpg")
                    val inputStream = holdingActivity!!.contentResolver.openInputStream(it)
                    val outputStream = FileOutputStream(file)
                    val byteArray = ByteArray(1024 * 500)
                    var readSize = -1
                    while (inputStream!!.read(byteArray).also { readSize = it } != -1) {
                        outputStream.write(byteArray, 0, readSize)
                    }
                    outputStream.flush()
                    inputStream.close()
                    outputStream.close()
                    Luban.with(context).load(file)
                        // 不压缩的阈值，单位为K
                        .ignoreBy(100)
                        .setCompressListener(object : OnCompressListener {
                            override fun onStart() {
                                // 压缩开始前调用，可以在方法内启动 loading UI
                            }

                            override fun onSuccess(file: File?) {
                                if (file == null || !file.exists()) {
                                    return
                                }
                                LogUtil.d("压缩后的文件大小${file.length() / 1024}kb")
                                // 压缩成功后调用，返回压缩后的图片文件
                                when (requestCode) {
                                    CAPTURE_ID_CARD_FRONT_PICTURE -> {
                                        Glide.with(holdingActivity!!).load(file)
                                            .into(binding!!.ivIdCardFront)
                                        (holdingActivity as MainActivity).idCardAndBankInfo.frontPhoto =
                                            Constants.BASE64_IMAGE_PREFIX +
                                                    Base64Util.toBase64String(file)
                                        binding!!.ivCameraIdCardFront.visibility = View.GONE
                                    }
                                    CAPTURE_ID_CARD_BACK_PICTURE -> {
                                        Glide.with(holdingActivity!!).load(file)
                                            .into(binding!!.ivIdCardBack)
                                        (holdingActivity as MainActivity).idCardAndBankInfo.backPhoto =
                                            Constants.BASE64_IMAGE_PREFIX +
                                                    Base64Util.toBase64String(file)
                                        binding!!.ivCameraIdCardBack.visibility = View.GONE
                                    }
                                    CAPTURE_BANK_PICTURE -> {
                                        Glide.with(holdingActivity!!).load(file)
                                            .into(binding!!.ivBankFront)
                                        (holdingActivity as MainActivity).idCardAndBankInfo.bankCardPhoto =
                                            Constants.BASE64_IMAGE_PREFIX +
                                                    Base64Util.toBase64String(file)
                                        binding!!.ivCameraBank.visibility = View.GONE
                                    }
                                    CAPTURE_SELF_PICTURE -> {
                                        Glide.with(holdingActivity!!).load(file)
                                            .into(binding!!.ivSelf)
                                        (holdingActivity as MainActivity).idCardAndBankInfo.selfie =
                                            Constants.BASE64_IMAGE_PREFIX +
                                                    Base64Util.toBase64String(file)
                                        binding!!.ivCameraSelf.visibility = View.GONE
                                    }
                                    else -> {
                                    }
                                }
                            }

                            override fun onError(e: Throwable?) {
                                // 当压缩过程出现问题时调用
                            }

                        }).launch()
                }
            }
        }
    }

}